import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, Image, 
  TouchableOpacity,BackHandler
} from 'react-native';
import Toast, {DURATION} from 'react-native-easy-toast';
import Picker from 'react-native-picker';
import BackButton from '../../component/BackButton';
import CommonCell from './CommonCell';
import DeviceStorage from '../../common/DeviceStorage'
import {jumpPage,createAreaData} from '../../common/common';
import {BASEURL} from '../../api/api'
var lastNavTime = "";
var lastNavTime2 = "";
var _this;
export default class PersCenter extends Component{
  static navigationOptions = ({ navigation }) =>{
    return{
      title:'个人信息',
      headerRight:(<View></View>),
      headerLeft:<BackButton navigation = {navigation}/>
    }
  };
  constructor(props){
    super(props);
    this.state = ({
      area:'',
      showPicker:false,
      userInfo:{
        nickname:'',
        userId:'',
      }
    })
    _this = this;
  }
  componentWillMount(){
    DeviceStorage.get('user').then((user)=>{
      if(user){
        let userInfo = JSON.parse(user);
        this.setState({
          //userId: userInfo.userId,
          userInfo:userInfo
        })
      } 
    })
    // DeviceStorage.get('nickName').then((nickName)=>{
    //   if(nickName){
    //     this.setState({
    //       nickName:nickName
    //     })
    //   } 
    // })
    // DeviceStorage.get('areaName').then((areaName)=>{
    //   if(areaName){
    //     this.setState({
    //       area:areaName
    //     })
    //   } 
    // })
  }
  componentDidMount(){
    BackHandler.addEventListener('hardwareBackPress', this._handleBackPress);
  }
  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress',this._handleBackPress);
  }
  _handleBackPress(){
    // /console.log(Picker)
    //alert(Picker.isPickerShow());
    //console.log('show', _this.state.showPicker);
    if(_this.state.showPicker){
      Picker.hide();
      _this.setState({showPicker: false});
      return true;
    } else {
      return false;
    }
  }
  _saveUser(userInfo){
    //console.log(BASEURL+'per/saveUserInfo?'+JSON.stringify(userInfo))
    fetch(BASEURL+'per/saveUserInfo?userId='+userInfo.userId+'&userCity='+userInfo.userCity)
    .then(res => res.json())
    .then(result => {
      console.log('res',result);
      if(result.succ == '1'){
        this.refs.toast.show("设置成功");
        //DeviceStorage.save("user",userInfo);
        DeviceStorage.save('user',JSON.stringify(userInfo));
        this.setState({
          userInfo: userInfo,
          showPicker: false,
        })
      }
    })
  }
  _showAreaPicker() {
    this.setState({showPicker:true});
    var {userInfo} = this.state;
    var cityArr = [];
    var province = "";
    var city = "";
    var county = "";
    let area = userInfo.userCity;
    if(area){
      province = area.split(' ')[0];
      city = area.split(' ')[1];
      county = area.split(' ')[2];
    }
    Picker.init({
        pickerData: createAreaData(),
        pickerTitleText:'城市选择',
        pickerCancelBtnText:'取消',
        pickerConfirmBtnText:'确定',
        pickerBg:[255,255,255,1],
        selectedValue: [province, city, county],
        onPickerConfirm: pickedValue => {
            //console.log('area--', pickedValue);
            
            let userCity = pickedValue[0] + ' ' + pickedValue[1] + ' ' + pickedValue[2];
            let userInfo = this.state.userInfo;
            userInfo.userCity = userCity;
            this._saveUser(userInfo);
        },
        onPickerCancel: pickedValue => {
          this.setState({showPicker:false});
            //console.log('area', pickedValue);
        },
        onPickerSelect: pickedValue => {
          this.setState({showPicker:false});
            //Picker.select(['山东', '青岛', '黄岛区'])
            //console.log('area', pickedValue);
        }
    });
    Picker.show();
  }
  _exit(){
    const {navigation} = this.props;
    //navigation.popToTop();
    //navigation.reset();
    if(navigation){
      DeviceStorage.delete('user');
      navigation.push('login');
    }
  }
  _cellPress(index){
    const {navigation} = this.props;
    const userInfo = this.state.userInfo;
    let title = '昵称修改';
    let text = this.state.userInfo.nickname;
    if(index == 2){
      title = '姓名'
      text = this.state.userInfo.userName;
    }
    if(index == 3){
      title = '性别'
      text = this.state.userInfo.userSex;
    }
    if(index == 6){
      title = '行业'
      text = this.state.userInfo.userIndustry;
    }
    if(index == 7){
      title = '企业名称'
      text = this.state.userInfo.userCompany;
    }
    if(index == 8){
      title = '职位'
      text = this.state.userInfo.userPost;
    }
    if(index == 9){
      title = '规模'
      text = this.state.userInfo.userScale;
    }
    if(index >= 1 && index <=3 || (index>5 && index < 10)){ //昵称
      if(lastNavTime+1000 >= Date.now()){
        return;
      }
      lastNavTime = Date.now();
      if(navigation){
        navigation.push('nickName',
          { text ,
            title,
            index,
            userId:this.state.userInfo.userId,
            callback: (data)=>{
              let userInfo = this.state.userInfo;
              if(index == 1) userInfo.nickname = data;
              if(index == 2) userInfo.userName = data;
              if(index == 3) userInfo.userSex = data;
              if(index == 6) userInfo.userIndustry = data;
              if(index == 7) userInfo.userCompany = data;
              if(index == 8) userInfo.userPost = data;
              if(index == 9) userInfo.userScale = data;
              DeviceStorage.save('user',JSON.stringify(userInfo));
              this.setState({
                userInfo: userInfo,
              })
            }
          });
      }
    } else if(index == 4){
      jumpPage(this.props.navigation, 'changePwd',{userId: userInfo.userId, password: userInfo.password});
    } else if(index == 5){ //城市
      this._showAreaPicker();
    } 
    /*
    else if(index == 6){ //手机
      if(lastNavTime2+1000 >= Date.now()){
        return;
      }
      lastNavTime2 = Date.now();
      if(navigation){
        navigation.push('phone',
          {phone:this.state.userInfo.phone,
            password:this.state.userInfo.password,
            userId:this.state.userInfo.userId,
            callback: (data)=>{
              let userInfo = this.state.userInfo;
              userInfo.phone = data;
              DeviceStorage.save('user',JSON.stringify(userInfo));
              this.setState({
                userInfo: userInfo,
              })
            }
          });
      }
    }
    */
  }
  render(){
    let {userInfo} = this.state;
    return(
      <View style={styles.container}>
        <View style={{height:10,backgroundColor:'#f0f0f0'}}></View>
        <CommonCell title='头像' rightImg={true} rightArrow={true}/>
        {/* <CommonCell title='昵称' rightText='2569874abc' activeOpacity={1}/> */}
        <CommonCell title='昵称' rightText={userInfo.nickname?userInfo.nickname:'未设置'} rightArrow={true} press={()=>this._cellPress(1)}/>
				<View style={{paddingTop:15,paddingBottom:15,backgroundColor:'#eee'}}>
          <Text style={{paddingLeft:10,fontSize:14, color: '#333'}}>完善信息</Text>
        </View>
				<CommonCell title='姓名' rightText={userInfo.userName?userInfo.userName:'未设置'} rightArrow={true} press={()=>this._cellPress(2)}/>
				<CommonCell title='性别' rightText={userInfo.userSex?userInfo.userSex:'未设置'} rightArrow={true} press={()=>this._cellPress(3)}/>
				<CommonCell title='城市' rightText={userInfo.userCity ? userInfo.userCity : '未设置'} rightArrow={true} press={()=>this._cellPress(5)}/>
				<CommonCell title='行业' rightText={userInfo.userIndustry?userInfo.userIndustry:'未设置'} rightArrow={true} press={()=>this._cellPress(6)}/>
				<CommonCell title='企业名称' rightText={userInfo.userCompany?userInfo.userCompany:'未设置'} rightArrow={true} press={()=>this._cellPress(7)}/>
				<CommonCell title='职位' rightText={userInfo.userPost?userInfo.userPost:'未设置'} rightArrow={true} press={()=>this._cellPress(8)}/>
				<CommonCell title='规模' rightText={userInfo.userScale?userInfo.userScale:'未设置'} rightArrow={true} press={()=>this._cellPress(9)}/>
        {/* <CommonCell title='修改密码' rightArrow={true} press={()=>this._cellPress(4)}/> */}
        
        {/* <CommonCell title='手机' rightText={this.state.userInfo.phone} rightArrow={true} press={()=>this._cellPress(6)}/>
        <View style={{height:20,backgroundColor:'#f0f0f0'}}></View>
        <TouchableOpacity style={styles.exitBtn} onPress={()=>{this._exit()}}>
          <Text style={styles.btnText}>退出登录</Text>
        </TouchableOpacity> */}
        <View style={{flex:1,backgroundColor:'#f0f0f0'}}></View>
        <Toast ref="toast" position='bottom' positionValue={200} />
      </View>
    )
  }
}
const styles = StyleSheet.create({
  btnText:{
    color:'#ff3f87',
    fontSize:16,
  },
  exitBtn:{
    padding:15,
    justifyContent:'center',
    alignItems:'center',
    backgroundColor:'white',
  },  
  container: {
    flex: 1,
    backgroundColor:'#fff',
  },
})